//
//  ClubForumDetailViewController.swift
//  77Club
//
//  Created by Apple on 2024/9/6.
//

import UIKit

class ClubForumDetailViewController: ClubBaseViewController, RaeAnimationProtocol {
    
    private let backButton = c_make_ex(UIButton.self)
        .image("Common_blackBack").end()
    private let userImageView = c_make_ex(UIImageView.self)
        .corner(16.0.Scale).mode(.scaleAspectFill).end()
    private let nameLabel = c_make_ex(UILabel.self)
        .color("#1A1A1A").font(12.font_semiBold).end()
    private let timeLabel = c_make_ex(UILabel.self)
        .color("#AFB1B3").font(10.font_medium).end()
    private let moreButton = c_make_ex(UIButton.self)
        .image("GameDetail_more").end()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubForumDetailTableViewCell.self,ClubDynamicDetailommitCell.self,ClubCommitEmptyCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 400.0.Scale
        return tableView
    }()
    private var bottomView = ClubForumDetailBottomView()
    private var commitView = ClubForumDetailCommitView()
    private var sortby = "1"
//    var updateDataBlock: (() -> Void)?
    var likeBlock:(()->())?
    
    var newId: String = "" {
        didSet{
            loadData()
        }
    }
    
    var communityId: String = "" {
        didSet{
            loadCommunityData()
        }
    }
    
    private var commitPid = ""
    private var commitPuid = ""
    private var commitNewsid = ""
    private var isEmptyCommit = false
    private var model: ClubGameCommunityDetailModel?
    private var commitModels: [ClubGameCommunityDetailCommentModel]?
    private var communityModel: ClubGameCommunityModel?
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // 禁用侧滑手势的代理
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)        
        // 恢复默认代理
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews {
            backButton
            userImageView
            nameLabel
            timeLabel
            moreButton
            tableView
            bottomView
            commitView
        }
        
        backButton.leading(0).top(.statusHeight).width(56).height(44)
        userImageView.leading(56).size(32.0.Scale)
        userImageView.CenterY == backButton.CenterY
        nameLabel.leading(100.0.Scale).trailing(90.0.Scale)
        nameLabel.Top == userImageView.Top + 2
        timeLabel.leading(100.0.Scale).trailing(90.0.Scale)
        timeLabel.Top == nameLabel.Bottom + 1.0.Scale
        moreButton.trailing(8).size(32)
        moreButton.CenterY == backButton.CenterY
        tableView.leading(0).trailing(0).top(.navi_height).bottom(82.0.Scale)
        bottomView.leading(0).trailing(0).height(82.0.Scale).bottom(0)
        commitView.leading(0).width(.screenWidth).height(47.0.Scale).bottom(.safe_bottom)
        
        commitView.isHidden = true
        tableView.isHidden = true
        
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        moreButton.addTarget(self, action: #selector(clickMoreButton), for: .touchUpInside)
        
        bottomView.showCommitView = {
            self.bottomView.isHidden = true
            self.commitView.isHidden = false
            self.commitView.commitView.becomeFirstResponder()
        }
        bottomView.likeBlock = {
            self.likeBlock?()
        }
        bottomView.shareBlock = {
            self.shareAction()
        }
        commitView.sendTextBlock = { content in
            self.sentCommit(text: content)
        }
        
        // 注册键盘通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }

    private func shareAction(){
        
        let moreView = ClubForumShareView()
        moreView.copyShareBlock = { type in
            self.shareDetail(type: type)
        }
        self.entryAnimate.animation(show: moreView)
    }
    
    private func shareDetail(type: Int) {
        if type == 3 {
            ClubGlobalTool.shared.shareToQQ(title: ClubGlobalTool.shared.dynamicShareTitle, description: ClubGlobalTool.shared.dynamicShareDes, imageUrl: "https://www.77.top/static/ios_logo.jpg", url: self.model?.share_url ?? "")
        }else if type == 4 {
            "分享口令已复制成功".toast_success
            let shareUrl = self.model?.share_url ?? ""
            UIPasteboard.general.string = shareUrl
        }else{
            ClubGlobalTool.shared.shareToWechat(title: ClubGlobalTool.shared.postShareTitle, des: self.model?.title ?? "", image: "AppIcon".toImage!, shareUrl: self.model?.share_url ?? "", shareType: type)
        }
    }
}

//MARK: action
extension ClubForumDetailViewController {
    
    private func loadData(){
        
        Task{
            ToastUtil.show()
            let res = await network.request(.strategyPostInfo(newID: newId),type: ClubGameCommunityDetailModel.self)
            ToastUtil.dismiss()
            if res.isSuccess, let model = res.model {
                self.model = model
                self.bottomView.model = model
                self.commitPid = self.model?.id ?? ""
                self.commitNewsid = self.model?.id ?? ""
                self.userImageView.loadImage(url: model.face)
                self.nameLabel.text = model.fabu
                self.timeLabel.text = model.time
                tableView.reloadData()
            }
        }
        
        var user_id = ""
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            user_id = uid
        }
        Task{
            let commitRes = await self.network.request(.strategyPostCommitList(newID: newId, uid: user_id, sortby: self.sortby),type: ClubGameCommunityDetailCommentModel.self)
            if commitRes.isSuccess, let models = commitRes.models {
                self.commitModels = models
                tableView.reloadData()
            }
        }
    }
    
    private func loadCommunityData(){
        Task {
            let res = await network.request(.communityTop(communityID: communityId),type: ClubGameCommunityModel.self)
            if res.isSuccess, let model = res.model {
                self.communityModel = model
            }
        }
    }
    
    private func loadCommitList(){
        
        var user_id = ""
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            user_id = uid
        }
        Task{
            let commitRes = await self.network.request(.strategyPostCommitList(newID: newId, uid: user_id, sortby: self.sortby),type: ClubGameCommunityDetailCommentModel.self)
            if commitRes.isSuccess, let models = commitRes.models {
                self.commitModels = models
                tableView.reloadSections(IndexSet(integer: 1), with: .none)
            }
        }
    }
    
    // 键盘消失时调用的方法
    @objc private func keyboardWillHide(_ notification: Notification) {
        guard let userInfo = notification.userInfo else { return }

        self.commitView.isHidden = true
        self.bottomView.isHidden = false
//        self.commitView.topConstraint?.constant = .screenHeight
        self.commitView.commitView.resignFirstResponder()
    }
    
    private func sentCommit(text: String){
        
        self.commitView.isHidden = true
        self.bottomView.isHidden = false
        self.commitView.commitView.resignFirstResponder()
        Task{
            var type = "0"
            if commitPuid.count > 0 {
                type = "1"
            }
            let res = await self.network.requestSpecialData(.addStrategyCommit(pid: self.commitPid, puid: commitPuid, type: type, content: text, news_id: self.commitNewsid), type: RaeNetworkBaseModel.self)
            if res.isSuccess {
                "评论成功".toast_success
                self.isEmptyCommit = false
                self.commitView.commitView.text = ""
                self.commitPid = self.model?.id ?? ""
                self.commitPuid = ""
                self.loadCommitList()
            }else{
                res.errorMessage?.toast_error
            }
        }
    }
    
    private func commitShare(commitID: String, uid: String){
        let moreView = ClubGameMoreView()
        moreView.uid_des = uid
        moreView.reportBlock = {
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                let reportVC = ClubReportViewController()
                reportVC.dynamicID = commitID
                reportVC.type = "2"
                self.present(reportVC, animated: true)
            }else{
                //登录
                self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
            }
        }
        moreView.delBlock = {
            Task{
                let res = await self.network.request(.delForumCommit(commitID: commitID))
                if res.isSuccess {
                    "删除成功".toast_success
                    self.loadCommitList()
                }
            }
        }

        self.entryAnimate.animation(show: moreView)
    }
    
    @objc private func clickMoreButton(){
        if let md = self.model {
            if (md.uid == "0" || md.uid.count == 0) && (self.communityModel?.my_role != 2 || self.communityModel?.my_role != 3){
                self.shareAction()
            }else{
                self.showMoreView(md: md)
            }
        }
    }
    
    private func showMoreView(md: ClubGameCommunityDetailModel){
        
        let moreView = ClubMoreView()
        var dataArr = [ClubMoreModel]()
        if self.communityModel?.my_role == 1 {
            if md.is_best {
                let mod = ClubMoreModel(title: "取消置顶此帖子",img: "ForumDetail_cancelTop",isRed: false,type: 2)
                dataArr.append(mod)
            }else{
                let mod = ClubMoreModel(title: "置顶此帖子",img: "ForumDetail_top",isRed: false,type: 1)
                dataArr.append(mod)
            }
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid == md.uid_des {
                let delModel = ClubMoreModel(title: "删除此帖子", img: "Home_more_del", isRed: true,type: 4)
                dataArr.append(delModel)
            }else{
                let mod = ClubMoreModel(title: "下架此帖子",img: "ForumDetail_down",isRed: false,type: 3)
                dataArr.append(mod)
            }
            moreView.dataSource = dataArr
        }else if self.communityModel?.my_role == 2{
                
            if self.communityModel?.perms?.perm_top == 1 {
                if md.is_best {
                    let mod = ClubMoreModel(title: "取消置顶此帖子",img: "ForumDetail_cancelTop",isRed: false,type: 2)
                    dataArr.append(mod)
                }else{
                    let mod = ClubMoreModel(title: "置顶此帖子",img: "ForumDetail_top",isRed: false,type: 1)
                    dataArr.append(mod)
                }
            }
            if self.communityModel?.perms?.perm_off == 1 {
                if let uid = UserDefaultsManager.getString(forKey: .uid), uid == md.uid_des {
                    let delModel = ClubMoreModel(title: "删除此帖子", img: "Home_more_del", isRed: true,type: 4)
                    dataArr.append(delModel)
                }else{
                    let mod = ClubMoreModel(title: "下架此帖子",img: "ForumDetail_down",isRed: false,type: 3)
                    dataArr.append(mod)
                }
            }else{
                if let uid = UserDefaultsManager.getString(forKey: .uid), uid == md.uid_des {
                    let delModel = ClubMoreModel(title: "删除此帖子", img: "Home_more_del", isRed: true,type: 4)
                    dataArr.append(delModel)
                }
            }
                
            moreView.dataSource = dataArr
        }else{
                
            moreView.isPost = true
            moreView.uid_des = md.uid_des
        }

        moreView.reportBlock = {
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                let reportVC = ClubReportViewController()
                reportVC.dynamicID = md.id
                reportVC.type = "0"
                reportVC.isShequ = true
                reportVC.updateDataBlock = {
                    self.navigationController?.popViewController(animated: true)
                }
                self.present(reportVC, animated: true)
            }else{
                //登录
                self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
            }
        }
        moreView.copyShareBlock = { type in
            self.shareDetail(type: type, model: md)
        }
        moreView.moreBlock = { type in
            if type == 3 {
                //下架
                Task {
                    let res = await self.network.request(.postUpOrDown(id: md.id))
                    if res.isSuccess {
                        self.likeBlock?()
                        self.navigationController?.popViewController(animated: true)
                    }
                }
            }else{
                //置顶或者取消置顶
                Task {
                    let res = await self.network.request(.postTopOrDown(id: md.id))
                    if res.isSuccess {
                        self.likeBlock?()
                    }
                }
            }
        }
        self.entryAnimate.animation(show: moreView)
        
    }
    
    private func shareDetail(type: Int, model: ClubGameCommunityDetailModel) {
        if type == 3 {
            ClubGlobalTool.shared.shareToQQ(title: ClubGlobalTool.shared.postShareTitle, description: model.title, imageUrl: "https://www.77.top/static/ios_logo.jpg", url: model.share_url)
        }else if type == 4 {
            "分享口令已复制成功".toast_success
            let shareUrl = self.model?.share_url ?? ""
            UIPasteboard.general.string = shareUrl
        }else{
            ClubGlobalTool.shared.shareToWechat(title: ClubGlobalTool.shared.postShareTitle, des: model.title, image: "AppIcon".toImage!, shareUrl: model.share_url, shareType: type)
        }
    }
}

//MARK: - UITableViewDelegate, UITableViewDataSource
extension ClubForumDetailViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if section == 0 {
            return 1
        }else{
            if let commitDatas = self.commitModels {
                if commitDatas.count == 0 {
                    self.isEmptyCommit = true
                    return 1
                }else{
                    return commitDatas.count
                }
            }
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubForumDetailTableViewCell", for: indexPath) as! ClubForumDetailTableViewCell
            cell.model = model
            cell.commitModel = self.commitModels
            cell.updateDataBlock = { md in
                self.model = md
                self.tableView.isHidden = false
                self.tableView.reloadData()
            }
            cell.sortByDataBlock = { type in
                self.sortby = type
                self.loadCommitList()
            }
            return cell
        }
        if self.isEmptyCommit {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubCommitEmptyCell", for: indexPath) as! ClubCommitEmptyCell
            cell.firstCommitBlock = {
                self.bottomView.isHidden = true
                self.commitView.isHidden = false
                self.commitView.commitView.becomeFirstResponder()
            }
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubDynamicDetailommitCell", for: indexPath) as! ClubDynamicDetailommitCell
            cell.forumModel = self.commitModels?[indexPath.row]
            cell.showMoreView = { commitID , uid in
                self.commitShare(commitID: commitID, uid: uid)
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 1 && !isEmptyCommit {
            guard let md = self.commitModels?[indexPath.row] else { return }
            self.commitView.commitView.placeHolder = "回复" + md.pet_name
            self.commitPid = md.id
            self.commitPuid = md.uid
            self.bottomView.isHidden = true
            self.commitView.isHidden = false
            self.commitView.commitView.becomeFirstResponder()
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
}
